package com.vt.admin.api.dto.user.structure;

import cn.hutool.core.collection.CollUtil;
import com.google.common.base.Joiner;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

import java.util.*;

/**
 * @Auther: PanZha
 * @Date: 2018/10/30 17:43
 */
@Data
@ApiModel("用户组织结构 组织、职位、角色")
public class UserOrganStructure {

    private List<StructureRowData> rows;

    public UserOrganStructure(List<UserOrganStructureItem> items) {

        String no = "no";
        //排序
        items = CollUtil.sortByProperty(items, no);
        //no 分组
        List<List<UserOrganStructureItem>> lists = CollUtil.groupByField(items, no);

        this.rows = new ArrayList(lists.size());
        for (List list : lists) {
            this.rows.add(new StructureRowData(list));
        }
    }

    /**
     * []{组织字符串, 职位字符串, 角色字符串}
     *
     * @return
     */
    public String[] textArray() {
        Set<String> s1 = new HashSet();
        Set<String> s2 = new HashSet();
        Set<String> s3 = new HashSet();

        for (StructureRowData row : rows) {
            s1.addAll(nameSet(row.getOrganizations()));
            s2.addAll(nameSet(row.getPositions()));
            s3.addAll(nameSet(row.getRoles()));
        }

        Joiner joiner = Joiner.on(",");
        return new String[]{
                joiner.join(s1),
                joiner.join(s2),
                joiner.join(s3)
        };
    }

    private Set nameSet(List<UserOrganStructureItem> list) {
        Set<String> names = new HashSet();
        if (null == list)
            return names;

        for (UserOrganStructureItem item : list) {
            names.add(item.getName());
        }
        return names;
    }

    @Data
    public class StructureRowData {

        private StructureRowData(List<UserOrganStructureItem> list) {
            List<List<UserOrganStructureItem>> lists = CollUtil.groupByField(list, "type");

            try {
                Collections.sort(lists, Comparator.comparingInt(list2 -> list2.get(0).getType()));

                this.organizations = lists.get(0);
                this.positions = lists.get(1);
                this.roles = lists.get(2);
            } catch (IndexOutOfBoundsException e) {
            }
        }

        @ApiModelProperty("组织")
        private List<UserOrganStructureItem> organizations;

        @ApiModelProperty("职位")
        private List<UserOrganStructureItem> positions;

        @ApiModelProperty("角色")
        private List<UserOrganStructureItem> roles;
    }
}
